<template>
  <div class="text-component" @dblclick="startEdit">
    <el-input
      v-if="isEditing"
      v-model="editContent"
      type="textarea"
      :autosize="{ minRows: 2 }"
      @blur="finishEdit"
      ref="editor"
      :style="{
        fontSize: `${component.fontSize || 14}px`,
        textAlign: component.textAlign || 'left'
      }"
    />
    <div v-else 
         class="text-content"
         :style="{
           fontSize: `${component.fontSize || 14}px`,
           textAlign: component.textAlign || 'left',
           minHeight: '24px'
         }"
         v-html="component.content">
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue'

const props = defineProps({
  component: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['update'])

const isEditing = ref(false)
const editContent = ref('')
const editor = ref(null)

// 开始编辑
const startEdit = (event) => {
  // 如果点击的是操作按钮，不触发编辑
  if (event.target.closest('.component-actions')) {
    return
  }
  
  editContent.value = props.component.content || ''
  isEditing.value = true
  
  // 等待 DOM 更新后聚焦输入框
  nextTick(() => {
    if (editor.value) {
      const textarea = editor.value.$el.querySelector('textarea')
      if (textarea) {
        textarea.focus()
        textarea.select()
      }
    }
  })
}

// 完成编辑
const finishEdit = () => {
  if (!isEditing.value) return
  
  isEditing.value = false
  if (editContent.value !== props.component.content) {
    emit('update', {
      ...props.component,
      content: editContent.value
    })
  }
}

// 监听按键事件
const handleKeyDown = (event) => {
  if (event.key === 'Enter' && event.ctrlKey) {
    finishEdit()
  } else if (event.key === 'Escape') {
    isEditing.value = false
    editContent.value = props.component.content || ''
  }
}
</script>

<style scoped>
.text-component {
  width: 100%;
  height: 100%;
  position: relative;
  cursor: text;
}

.text-content {
  width: 100%;
  height: 100%;
  padding: 8px;
  white-space: pre-wrap;
  word-break: break-word;
  overflow: auto;
}

:deep(.el-textarea) {
  width: 100%;
  height: 100%;
}

:deep(.el-textarea__inner) {
  height: 100%;
  padding: 8px;
  resize: none;
  font-family: inherit;
  line-height: inherit;
  background-color: transparent;
}

:deep(.el-textarea__inner:focus) {
  box-shadow: none;
}

/* 暗色主题适配 */
@media (prefers-color-scheme: dark) {
  .text-content {
    color: var(--theme-text-color, #e2e8f0);
  }
  
  :deep(.el-textarea__inner) {
    color: var(--theme-text-color, #e2e8f0);
    background-color: var(--theme-container-bg, #1e293b);
    border-color: var(--theme-border-color, #334155);
  }
}
</style> 